#include "Task.hpp"
#include "Ringqueue.hpp"
#include <ctime>
class ThreadData
{
public:
    string threadname;
    RingQueue<Task>* rq;
};

void* Productor(void* args)
{
    ThreadData* tn=static_cast<ThreadData*>(args);
    string name=tn->threadname;

    while(1)
    {
        int x=rand()%10+1;//[1,10]
        usleep(20);//防止产生的值，相似
        int y=rand()%15;
        char oper=opers[rand()%opers.size()];

        Task t(x,y,oper);
        tn->rq->Push(t);

        cout<< "Productor task done, task is : " << t.GetTask() << " who: " << name << endl;
    }
}

void* Consumer(void* args)
{
    ThreadData* tn=static_cast<ThreadData*>(args);
    string name=tn->threadname;

    while(1)
    {
        Task t=tn->rq->Pop();
        t();//运算

        cout << "Consumer get task, task is : " << t.GetTask()
         << " who: " << name << " result: " << t.GetResult() << endl;
         sleep(1);
    }
}

int main()
{
    srand(time(nullptr));

    RingQueue<Task>* rq=new RingQueue<Task>();

    pthread_t p[2],c[3];

    for (int i = 0; i < 2; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Productor-" + std::to_string(i);
        pthread_create(p + i, nullptr, Productor, td);
    }
    
    for (int i = 0; i < 3; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname= "Consumer-" + std::to_string(i);

        pthread_create(c + i, nullptr, Consumer, td);
    }

    for (int i = 0; i < 2; i++)
    {
        pthread_join(p[i], nullptr);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }
    
    return 0;
}